package br.com.skolar.client;

import java.util.Collection;

import br.com.skolar.client.events.LoadAnswersEvent;
import br.com.skolar.client.events.QuestionsLoadedEvent;
import br.com.skolar.client.events.SaveAnswerEvent;
import br.com.skolar.client.events.SaveQuestionEvent;
import br.com.skolar.client.events.SearchQuestionsEvent;
import br.com.skolar.client.framework.Event;
import br.com.skolar.client.framework.EventBus;
import br.com.skolar.client.framework.ParamCommand;
import br.com.skolar.client.view.QuestionsView;

import com.google.inject.Inject;

public class SkolarPresenter {
	@Inject
	public SkolarPresenter(final Skolar.Injector injector, QuestionsView view, 
			final EventBus eventBus, final QuestionServiceAsync service) {
		eventBus.addHandler(SearchQuestionsEvent.class, new Event.Handler<SearchQuestionsEvent>() {
			@Override
			public void onEvent(SearchQuestionsEvent e) {
				service.searchQuestions(injector.callback()
				.onSuccess(e, new ParamCommand<Collection<Question>>() {
					@Override
					public void execute(Collection<Question> questions) {
						eventBus.fireEvent(new QuestionsLoadedEvent(questions));
					}
				}));
			}
		});
		
		eventBus.addHandler(SaveQuestionEvent.class, new Event.Handler<SaveQuestionEvent>() {
			@Override
			public void onEvent(SaveQuestionEvent e) {
				service.save(e.question, injector.callback().showSuccessMessage().onSuccess(e));
			}
		});

		eventBus.addHandler(SaveAnswerEvent.class, new Event.Handler<SaveAnswerEvent>() {
			@Override
			public void onEvent(SaveAnswerEvent e) {
				service.save(e.answer, injector.callback().showSuccessMessage().onSuccess(e));
			}
		});

		eventBus.addHandler(LoadAnswersEvent.class, new Event.Handler<LoadAnswersEvent>() {
			@Override
			public void onEvent(LoadAnswersEvent e) {
				service.loadAnswers(e.question, injector.callback().onSuccess(e));
			}
		});
	}
}